package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.exception.UserException;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
public class TestController {
    @Autowired
    UserMapper userMapper;


    @ResponseBody
    @RequestMapping("user/{id}")
    public User user(@PathVariable int id){
        User user = userMapper.getUser(id);
        return user;
    }

    @ResponseBody
    @RequestMapping("user/add")
    public String add(@Validated User user, BindingResult bindResult){
        // 如果有错误
        if (bindResult.hasErrors()) {
            // 返回提示信息
            throw new UserException(402,bindResult.getFieldError().getDefaultMessage());
        }
        if(user.getAge() == 18){
            throw new UserException(401);
        }
        userMapper.add(user);
        return "添加成功";
    }


}
